{% extends "base.html" %}

{% block title %}系统设置 - MinerU 文档解析系统{% endblock %}

{% block page_title %}系统设置{% endblock %}

{% block content %}
<div class="fade-in">
    <!-- 设置导航 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <div class="flex items-center space-x-6">
            <button onclick="showSettingsTab('general')" class="settings-tab-btn active px-4 py-2 rounded-lg font-medium text-sm">
                <i class="fas fa-cog mr-2"></i>基础设置
            </button>
            <button onclick="showSettingsTab('security')" class="settings-tab-btn px-4 py-2 rounded-lg font-medium text-sm">
                <i class="fas fa-shield-alt mr-2"></i>安全设置
            </button>
            <button onclick="showSettingsTab('upload')" class="settings-tab-btn px-4 py-2 rounded-lg font-medium text-sm">
                <i class="fas fa-upload mr-2"></i>上传设置
            </button>
            <button onclick="showSettingsTab('parser')" class="settings-tab-btn px-4 py-2 rounded-lg font-medium text-sm">
                <i class="fas fa-file-alt mr-2"></i>解析设置
            </button>
            <button onclick="showSettingsTab('system')" class="settings-tab-btn px-4 py-2 rounded-lg font-medium text-sm">
                <i class="fas fa-server mr-2"></i>系统设置
            </button>
        </div>
    </div>
    
    <!-- 基础设置 -->
    <div id="general-settings" class="settings-tab">
        <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">基础设置</h3>
            
            <div class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">系统名称</label>
                        <input type="text" id="appName" value="MinerU 文档解析服务" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">系统版本</label>
                        <input type="text" id="appVersion" value="1.0.0" readonly
                               class="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-50">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">监听地址</label>
                        <input type="text" id="host" value="0.0.0.0" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">监听端口</label>
                        <input type="number" id="port" value="8000" min="1" max="65535"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                
                <div>
                    <label class="flex items-center">
                        <input type="checkbox" id="debugMode" class="mr-2">
                        <span class="text-sm text-gray-700">启用调试模式</span>
                    </label>
                    <p class="text-xs text-gray-500 mt-1">调试模式会显示详细的错误信息，生产环境建议关闭</p>
                </div>
            </div>
            
            <div class="mt-6 flex justify-end">
                <button onclick="saveGeneralSettings()" class="btn-primary text-white px-6 py-2 rounded-md hover:bg-blue-700">
                    <i class="fas fa-save mr-2"></i>保存设置
                </button>
            </div>
        </div>
    </div>
    
    <!-- 安全设置 -->
    <div id="security-settings" class="settings-tab hidden">
        <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">安全设置</h3>
            
            <div class="space-y-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">JWT 密钥</label>
                    <div class="flex items-center space-x-2">
                        <input type="password" id="jwtSecret" value="your-secret-key-change-in-production" 
                               class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <button onclick="togglePassword('jwtSecret')" class="px-3 py-2 border border-gray-300 rounded-md hover:bg-gray-50">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button onclick="generateJwtSecret()" class="px-3 py-2 border border-gray-300 rounded-md hover:bg-gray-50">
                            <i class="fas fa-refresh"></i>
                        </button>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">用于JWT令牌签名的密钥，建议使用强密码</p>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">JWT 过期时间</label>
                        <select id="jwtExpire" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="3600">1小时</option>
                            <option value="7200">2小时</option>
                            <option value="21600">6小时</option>
                            <option value="43200">12小时</option>
                            <option value="86400">24小时</option>
                            <option value="604800">7天</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">CORS 允许的源</label>
                        <input type="text" id="corsOrigins" value="*" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <p class="text-xs text-gray-500 mt-1">多个源用逗号分隔，*表示允许所有源</p>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">限流请求数</label>
                        <input type="number" id="rateLimitRequests" value="100" min="1" max="10000"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">限流时间窗口</label>
                        <select id="rateLimitWindow" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="60">1分钟</option>
                            <option value="300">5分钟</option>
                            <option value="600">10分钟</option>
                            <option value="3600">1小时</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="mt-6 flex justify-end">
                <button onclick="saveSecuritySettings()" class="btn-primary text-white px-6 py-2 rounded-md hover:bg-blue-700">
                    <i class="fas fa-save mr-2"></i>保存设置
                </button>
            </div>
        </div>
    </div>
    
    <!-- 上传设置 -->
    <div id="upload-settings" class="settings-tab hidden">
        <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">上传设置</h3>
            
            <div class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">上传目录</label>
                        <input type="text" id="uploadDir" value="uploads" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">最大文件大小</label>
                        <div class="flex items-center space-x-2">
                            <input type="number" id="maxFileSize" value="50" min="1" max="1000"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <span class="text-sm text-gray-500">MB</span>
                        </div>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">允许的文件类型</label>
                    <div class="space-y-2">
                        <label class="flex items-center">
                            <input type="checkbox" value=".pdf" checked class="mr-2 file-extension">
                            <span class="text-sm text-gray-700">PDF 文档</span>
                        </label>
                        <label class="flex items-center">
                            <input type="checkbox" value=".doc" checked class="mr-2 file-extension">
                            <span class="text-sm text-gray-700">Word 文档 (.doc)</span>
                        </label>
                        <label class="flex items-center">
                            <input type="checkbox" value=".docx" checked class="mr-2 file-extension">
                            <span class="text-sm text-gray-700">Word 文档 (.docx)</span>
                        </label>
                        <label class="flex items-center">
                            <input type="checkbox" value=".xls" checked class="mr-2 file-extension">
                            <span class="text-sm text-gray-700">Excel 文件 (.xls)</span>
                        </label>
                        <label class="flex items-center">
                            <input type="checkbox" value=".xlsx" checked class="mr-2 file-extension">
                            <span class="text-sm text-gray-700">Excel 文件 (.xlsx)</span>
                        </label>
                        <label class="flex items-center">
                            <input type="checkbox" value=".ppt" checked class="mr-2 file-extension">
                            <span class="text-sm text-gray-700">PowerPoint 文件 (.ppt)</span>
                        </label>
                        <label class="flex items-center">
                            <input type="checkbox" value=".pptx" checked class="mr-2 file-extension">
                            <span class="text-sm text-gray-700">PowerPoint 文件 (.pptx)</span>
                        </label>
                    </div>
                </div>
            </div>
            
            <div class="mt-6 flex justify-end">
                <button onclick="saveUploadSettings()" class="btn-primary text-white px-6 py-2 rounded-md hover:bg-blue-700">
                    <i class="fas fa-save mr-2"></i>保存设置
                </button>
            </div>
        </div>
    </div>
    
    <!-- 解析设置 -->
    <div id="parser-settings" class="settings-tab hidden">
        <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">解析设置</h3>
            
            <div class="space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">结果保存目录</label>
                        <input type="text" id="parsedResultsDir" value="parsed_results" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">结果保留天数</label>
                        <input type="number" id="resultsRetentionDays" value="90" min="1" max="365"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">最大并发任务数</label>
                        <input type="number" id="maxConcurrentTasks" value="10" min="1" max="100"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">任务超时时间</label>
                        <div class="flex items-center space-x-2">
                            <input type="number" id="taskTimeout" value="300" min="60" max="3600"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <span class="text-sm text-gray-500">秒</span>
                        </div>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">MinerU 模型路径</label>
                        <input type="text" id="mineruModelPath" placeholder="可选，留空使用默认路径" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">运行设备</label>
                        <select id="mineruDevice" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="cpu">CPU</option>
                            <option value="cuda">CUDA (GPU)</option>
                            <option value="mps">MPS (Apple Silicon)</option>
                        </select>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">默认OCR引擎</label>
                    <select id="defaultOcrEngine" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="paddle">PaddleOCR</option>
                        <option value="rapid">RapidOCR</option>
                        <option value="tesseract">Tesseract</option>
                    </select>
                </div>
            </div>
            
            <div class="mt-6 flex justify-end">
                <button onclick="saveParserSettings()" class="btn-primary text-white px-6 py-2 rounded-md hover:bg-blue-700">
                    <i class="fas fa-save mr-2"></i>保存设置
                </button>
            </div>
        </div>
    </div>
    
    <!-- 系统设置 -->
    <div id="system-settings" class="settings-tab hidden">
        <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">系统设置</h3>
            
            <div class="space-y-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">日志级别</label>
                    <select id="logLevel" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="DEBUG">DEBUG</option>
                        <option value="INFO" selected>INFO</option>
                        <option value="WARNING">WARNING</option>
                        <option value="ERROR">ERROR</option>
                        <option value="CRITICAL">CRITICAL</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">日志文件路径</label>
                    <input type="text" id="logFile" value="logs/app.log" 
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Redis 连接</label>
                    <input type="text" id="redisUrl" placeholder="可选，例如：redis://localhost:6379/0" 
                           class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <p class="text-xs text-gray-500 mt-1">用于缓存和任务队列，可选配置</p>
                </div>
            </div>
            
            <div class="mt-6 flex justify-end">
                <button onclick="saveSystemSettings()" class="btn-primary text-white px-6 py-2 rounded-md hover:bg-blue-700">
                    <i class="fas fa-save mr-2"></i>保存设置
                </button>
            </div>
        </div>
        
        <!-- 系统操作 -->
        <div class="bg-white rounded-xl shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">系统操作</h3>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <button onclick="restartSystem()" class="bg-orange-500 text-white px-4 py-2 rounded-md hover:bg-orange-600">
                    <i class="fas fa-restart mr-2"></i>重启系统
                </button>
                
                <button onclick="clearCache()" class="bg-yellow-500 text-white px-4 py-2 rounded-md hover:bg-yellow-600">
                    <i class="fas fa-broom mr-2"></i>清理缓存
                </button>
                
                <button onclick="cleanupOldResults()" class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600">
                    <i class="fas fa-trash mr-2"></i>清理过期结果
                </button>
                
                <button onclick="exportConfig()" class="bg-green-500 text-white px-4 py-2 rounded-md hover:bg-green-600">
                    <i class="fas fa-download mr-2"></i>导出配置
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 确认对话框 -->
<div id="confirmModal" class="modal fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
    <div class="relative top-20 mx-auto p-5 border w-11/12 max-w-md shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800">确认操作</h3>
                <button onclick="closeConfirmModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <p id="confirmMessage" class="text-sm text-gray-600 mb-4"></p>
            
            <div class="flex justify-end space-x-3">
                <button onclick="closeConfirmModal()" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
                    取消
                </button>
                <button id="confirmButton" class="btn-primary text-white px-4 py-2 rounded-md hover:bg-blue-700">
                    确认
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let currentConfirmAction = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadSettings();
});

// 加载设置
async function loadSettings() {
    try {
        const settings = await apiRequest('/api/v1/admin/settings');
        
        // 基础设置
        document.getElementById('appName').value = settings.app_name || 'MinerU 文档解析服务';
        document.getElementById('appVersion').value = settings.app_version || '1.0.0';
        document.getElementById('host').value = settings.host || '0.0.0.0';
        document.getElementById('port').value = settings.port || 8000;
        document.getElementById('debugMode').checked = settings.debug || false;
        
        // 安全设置
        document.getElementById('jwtSecret').value = settings.jwt_secret_key || 'your-secret-key-change-in-production';
        document.getElementById('jwtExpire').value = settings.jwt_expire_seconds || 3600;
        document.getElementById('corsOrigins').value = Array.isArray(settings.cors_origins) ? settings.cors_origins.join(', ') : '*';
        document.getElementById('rateLimitRequests').value = settings.rate_limit_requests || 100;
        document.getElementById('rateLimitWindow').value = settings.rate_limit_window || 60;
        
        // 上传设置
        document.getElementById('uploadDir').value = settings.upload_dir || 'uploads';
        document.getElementById('maxFileSize').value = settings.max_file_size / (1024 * 1024) || 50;
        
        // 文件扩展名
        const extensions = settings.allowed_extensions || ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'];
        document.querySelectorAll('.file-extension').forEach(checkbox => {
            checkbox.checked = extensions.includes(checkbox.value);
        });
        
        // 解析设置
        document.getElementById('parsedResultsDir').value = settings.parsed_results_dir || 'parsed_results';
        document.getElementById('resultsRetentionDays').value = settings.results_retention_days || 90;
        document.getElementById('maxConcurrentTasks').value = settings.max_concurrent_tasks || 10;
        document.getElementById('taskTimeout').value = settings.task_timeout_seconds || 300;
        document.getElementById('mineruModelPath').value = settings.mineru_model_path || '';
        document.getElementById('mineruDevice').value = settings.mineru_device || 'cpu';
        document.getElementById('defaultOcrEngine').value = settings.default_ocr_engine || 'paddle';
        
        // 系统设置
        document.getElementById('logLevel').value = settings.log_level || 'INFO';
        document.getElementById('logFile').value = settings.log_file || 'logs/app.log';
        document.getElementById('redisUrl').value = settings.redis_url || '';
        
    } catch (error) {
        console.error('加载设置失败:', error);
        showNotification('加载设置失败', 'error');
    }
}

// 切换设置标签
function showSettingsTab(tabName) {
    // 隐藏所有标签
    document.querySelectorAll('.settings-tab').forEach(tab => {
        tab.classList.add('hidden');
    });
    
    // 移除所有按钮的active状态
    document.querySelectorAll('.settings-tab-btn').forEach(btn => {
        btn.classList.remove('active', 'bg-blue-100', 'text-blue-700');
        btn.classList.add('text-gray-600', 'hover:text-gray-800');
    });
    
    // 显示选中的标签
    document.getElementById(`${tabName}-settings`).classList.remove('hidden');
    
    // 激活对应的按钮
    event.target.classList.add('active', 'bg-blue-100', 'text-blue-700');
    event.target.classList.remove('text-gray-600', 'hover:text-gray-800');
}

// 保存基础设置
async function saveGeneralSettings() {
    try {
        const settings = {
            app_name: document.getElementById('appName').value,
            host: document.getElementById('host').value,
            port: parseInt(document.getElementById('port').value),
            debug: document.getElementById('debugMode').checked
        };
        
        await apiRequest('/api/v1/admin/settings', {
            method: 'PUT',
            body: JSON.stringify(settings)
        });
        
        showNotification('基础设置保存成功', 'success');
    } catch (error) {
        console.error('保存基础设置失败:', error);
        showNotification('保存基础设置失败', 'error');
    }
}

// 保存安全设置
async function saveSecuritySettings() {
    try {
        const settings = {
            jwt_secret_key: document.getElementById('jwtSecret').value,
            jwt_expire_seconds: parseInt(document.getElementById('jwtExpire').value),
            cors_origins: document.getElementById('corsOrigins').value.split(',').map(s => s.trim()),
            rate_limit_requests: parseInt(document.getElementById('rateLimitRequests').value),
            rate_limit_window: parseInt(document.getElementById('rateLimitWindow').value)
        };
        
        await apiRequest('/api/v1/admin/settings', {
            method: 'PUT',
            body: JSON.stringify(settings)
        });
        
        showNotification('安全设置保存成功', 'success');
    } catch (error) {
        console.error('保存安全设置失败:', error);
        showNotification('保存安全设置失败', 'error');
    }
}

// 保存上传设置
async function saveUploadSettings() {
    try {
        const extensions = Array.from(document.querySelectorAll('.file-extension:checked'))
            .map(cb => cb.value);
        
        const settings = {
            upload_dir: document.getElementById('uploadDir').value,
            max_file_size: parseInt(document.getElementById('maxFileSize').value) * 1024 * 1024,
            allowed_extensions: extensions
        };
        
        await apiRequest('/api/v1/admin/settings', {
            method: 'PUT',
            body: JSON.stringify(settings)
        });
        
        showNotification('上传设置保存成功', 'success');
    } catch (error) {
        console.error('保存上传设置失败:', error);
        showNotification('保存上传设置失败', 'error');
    }
}

// 保存解析设置
async function saveParserSettings() {
    try {
        const settings = {
            parsed_results_dir: document.getElementById('parsedResultsDir').value,
            results_retention_days: parseInt(document.getElementById('resultsRetentionDays').value),
            max_concurrent_tasks: parseInt(document.getElementById('maxConcurrentTasks').value),
            task_timeout_seconds: parseInt(document.getElementById('taskTimeout').value),
            mineru_model_path: document.getElementById('mineruModelPath').value,
            mineru_device: document.getElementById('mineruDevice').value,
            default_ocr_engine: document.getElementById('defaultOcrEngine').value
        };
        
        await apiRequest('/api/v1/admin/settings', {
            method: 'PUT',
            body: JSON.stringify(settings)
        });
        
        showNotification('解析设置保存成功', 'success');
    } catch (error) {
        console.error('保存解析设置失败:', error);
        showNotification('保存解析设置失败', 'error');
    }
}

// 保存系统设置
async function saveSystemSettings() {
    try {
        const settings = {
            log_level: document.getElementById('logLevel').value,
            log_file: document.getElementById('logFile').value,
            redis_url: document.getElementById('redisUrl').value
        };
        
        await apiRequest('/api/v1/admin/settings', {
            method: 'PUT',
            body: JSON.stringify(settings)
        });
        
        showNotification('系统设置保存成功', 'success');
    } catch (error) {
        console.error('保存系统设置失败:', error);
        showNotification('保存系统设置失败', 'error');
    }
}

// 重启系统
function restartSystem() {
    showConfirmModal('确定要重启系统吗？这将中断所有正在进行的任务。', async () => {
        try {
            await apiRequest('/api/v1/admin/system/restart', { method: 'POST' });
            showNotification('系统重启指令已发送', 'success');
        } catch (error) {
            console.error('重启系统失败:', error);
            showNotification('重启系统失败', 'error');
        }
    });
}

// 清理缓存
function clearCache() {
    showConfirmModal('确定要清理缓存吗？', async () => {
        try {
            await apiRequest('/api/v1/admin/system/clear-cache', { method: 'POST' });
            showNotification('缓存清理成功', 'success');
        } catch (error) {
            console.error('清理缓存失败:', error);
            showNotification('清理缓存失败', 'error');
        }
    });
}

// 清理过期结果
function cleanupOldResults() {
    showConfirmModal('确定要清理过期的解析结果吗？', async () => {
        try {
            await apiRequest('/api/v1/admin/system/cleanup-results', { method: 'POST' });
            showNotification('过期结果清理成功', 'success');
        } catch (error) {
            console.error('清理过期结果失败:', error);
            showNotification('清理过期结果失败', 'error');
        }
    });
}

// 导出配置
async function exportConfig() {
    try {
        const response = await apiRequest('/api/v1/admin/settings/export');
        
        const blob = new Blob([JSON.stringify(response, null, 2)], { type: 'application/json' });
        const downloadUrl = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = `config_${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(downloadUrl);
        document.body.removeChild(a);
        
        showNotification('配置导出成功', 'success');
    } catch (error) {
        console.error('导出配置失败:', error);
        showNotification('导出配置失败', 'error');
    }
}

// 工具函数
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const type = input.type === 'password' ? 'text' : 'password';
    input.type = type;
}

function generateJwtSecret() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
    let secret = '';
    for (let i = 0; i < 32; i++) {
        secret += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    document.getElementById('jwtSecret').value = secret;
}

function showConfirmModal(message, onConfirm) {
    document.getElementById('confirmMessage').textContent = message;
    document.getElementById('confirmModal').classList.remove('hidden');
    currentConfirmAction = onConfirm;
}

function closeConfirmModal() {
    document.getElementById('confirmModal').classList.add('hidden');
    currentConfirmAction = null;
}

// 确认按钮事件
document.getElementById('confirmButton').addEventListener('click', () => {
    if (currentConfirmAction) {
        currentConfirmAction();
    }
    closeConfirmModal();
});
</script>

<style>
.settings-tab-btn.active {
    @apply bg-blue-100 text-blue-700;
}
</style>
{% endblock %}